﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using B.S.Filtration.Domain.工单;
using B.S.Filtration.Read.Api.Application.Command.SaleCommand;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using Dm.util;
using B.S.Filtration.ErrorCode;

namespace B.S.Filtration.Read.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SaleController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ISqlSugarClient db;

        public SaleController(IMediator mediator, ISqlSugarClient db)
        {
            this.mediator = mediator;
            this.db = db;
        }


        /// <summary>
        /// 查询销售记录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<List<Sale>>> QuerySale([FromQuery] QuerySaleCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 查询销售记录(单条)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<Sale>>> ShowSale([FromQuery] ShowSaleCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 导出方法
        /// </summary>
        /// <returns>返回任务</returns>
        [HttpGet]
        public ActionResult ExportToExcel()
        {
            try
            {

                // 模拟查询数据，这里假设查询 User 表
                var data = db.Queryable<Sale>().ToList();

                // 创建一个新的 Excel 工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在Excel文件中创建工作表
                ISheet sheet = wb.CreateSheet("计划表");

                //在工作表中创建行(第一行,标题);
                IRow row = sheet.CreateRow(0);

                //创建单元格
                row.CreateCell(0).SetCellValue("联系记录主键");
                row.CreateCell(1).SetCellValue("销售日期");
                row.CreateCell(2).SetCellValue("客户名称");
                row.CreateCell(3).SetCellValue("产品名称");
                row.CreateCell(4).SetCellValue("销售数量");
                row.CreateCell(5).SetCellValue("销售单价");
                row.CreateCell(6).SetCellValue("销售额");
                row.CreateCell(7).SetCellValue("销售人员");
                row.CreateCell(8).SetCellValue("销售渠道");
                row.CreateCell(9).SetCellValue("付款方式");
                row.CreateCell(10).SetCellValue("备注");
                row.CreateCell(11).SetCellValue("是否删除");

                var index = 1;
                foreach (var item in data)
                {
                    row = sheet.CreateRow(index);

                    row.CreateCell(0).SetCellValue(item.SaleId.ToString());
                    row.CreateCell(1).SetCellValue(item.SaleDate.ToString("yyyy-MM-dd"));
                    row.CreateCell(2).SetCellValue(item.CustomerName);
                    row.CreateCell(3).SetCellValue(item.ProductName);
                    row.CreateCell(4).SetCellValue(item.SaleSum);
                    row.CreateCell(5).SetCellValue(item.SalePrice.ToString());
                    row.CreateCell(6).SetCellValue(item.Sales.ToString());
                    row.CreateCell(7).SetCellValue(item.Salespeople);
                    row.CreateCell(8).SetCellValue(item.SalesChannels);
                    row.CreateCell(9).SetCellValue(item.PaymentMethods);
                    row.CreateCell(10).SetCellValue(item.Remark);
                    row.CreateCell(11).SetCellValue(item.Del ? "删除" : "未删除");

                    index++;
                }

                //Excel的值
                byte[] buffer;
                //通过内存流读出Excel内容,转换为二进制数组
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    buffer = ms.ToArray();
                }

                //导出Excel  using  Microsoft.AspNetCore.StaticFiles;
                string excelMime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //导出
                return File(buffer, excelMime, "计划 表.xlsx");
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"导出 Excel 时出错: {ex.Message}");
            }

            return new EmptyResult();
        }
    }
}
